package com.bc.mcode.controller;

import com.bc.mcode.collect.Lists;
import com.bc.mcode.core.ClockManager;
import com.bc.mcode.core.ClockResponse;
import com.bc.mcode.model.ClockVO;
import com.bc.mcode.service.ClockVOService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ClockInitListener implements ApplicationListener<ContextRefreshedEvent> {
	protected Logger log = LogManager.getLogger(getClass().getName());
	@Autowired
	private ClockVOService clockVOService;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent evt) {
		initClock();
	}

    public Date getDate(String str)  {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = simpleDateFormat.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

	/**
	 * 根据状态查询数据
	 * @param state 1 未发送的 2成功的 3失败的
	 * @return
	 */
	public List<ClockVO> getClockData(int state){
		ClockVO clockVO = new ClockVO();
		clockVO.setClockState(state);
		clockVO.setCallTime(3);
		/*DataTableParamVO paramVO = new DataTableParamVO(null,null,"clockVO",clockVO);
		return  clockVOService.queryDataList(paramVO);*/
		return  null;
	}

	public void initClock() {

        Date date = new Date();
        long nowTime = date.getTime();
		ClockManager manger = ClockManager.getInstance();
		List<ClockVO> dataList = getClockData(1);
        List<ClockVO> dataFailList = getClockData(3);
        List<ClockVO> outDataList = Lists.newArrayList();

		for (int i= 0; i< dataList.size();i++){
		    ClockVO clockVO = dataList.get(i);
		    long dataTime = getDate(clockVO.getClockTime()).getTime();
		    //超时的进入失败队列
		    if(nowTime >= dataTime){
                outDataList.add(clockVO);
                //否则进入待发送队列
            }else{
                manger.addClockVO(clockVO);
            }
		}

		ClockResponse cResponse = ClockResponse.getInstance();
		for (int i=0;i<outDataList.size();i++){
            cResponse.addClockVO(outDataList.get(i));
        }

		for (int i= 0; i< dataFailList.size();i++){
			cResponse.addClockVO(dataFailList.get(i));
		}
		log.info("ClockManager init size:" + manger.getDataNum());
        log.info("ClockResponse init size:" + cResponse.getTotalDataNum());
		manger.start();
		cResponse.start();
	}
}
